const state = {
  // 页面进来时优先使用旧数据, 如果没有再给默认空数组
  list: uni.getStorageSync('cart') || []
}
const mutations = {
  // 添加进购物车
  addCart (state, product) {
    // 添加逻辑不仅仅push 需要判断原本是否存在
    // 存在 就 number += 1, 否则才 push
    const prodFound = state.list.find(item=>item.goods_id === product.goods_id)
    if (prodFound) {
      prodFound.number += 1
    }else{
      state.list.push(product)
    }

    // 每当修改时备份数据
    uni.setStorageSync('cart', state.list)
  },
  // 切换选中状态
  toggleCheck(state, goods_id) {
    // 切换选中状态, 接收一个商品 id, 在列表中找出该商品
    // 将他的 isChecked 属性取反
    const prodFound = state.list.find(item=>item.goods_id===goods_id)
    prodFound.isChecked = !prodFound.isChecked
    // 数据持久化备份
    uni.setStorageSync('cart', state.list)
  },
  // 加一 减一 (数量的变化) 可以传入一个对象 {goodsId, number}
  changeNumber(state, data) {
    const prodFound = state.list.find(item=>item.goods_id === data.goods_id)
    prodFound.number = data.number
    uni.setStorageSync('cart', state.list)
  },
  delGoods(state, goods_id) {
    const index = state.list.findIndex(item=>item.goods_id === goods_id)
    state.list.splice(index, 1)
    uni.setStorageSync('cart', state.list)
  },
  toggleAllCheck(state) {
    const isAllChecked = state.list.every(item=>item.isChecked)
    const checkAll = () => {
      state.list.forEach(element => {
        element.isChecked = true
      });
    }
    const unCheckAll = () => {
      state.list.forEach(element => {
        element.isChecked = false
      });
    }
    isAllChecked ? unCheckAll() : checkAll()
    uni.setStorageSync('cart', state.list)
  },
  clearCart(state) {
    // 购买后清理买过的产品
    // 留在购物车的都应该是当前没有选中的产品
    const newList = state.list.filter(item=>!item.isChecked)
    state.list = newList
    uni.setStorageSync('cart', state.list)
  }
}
const actions = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}